package demo3;

import java.util.*;
//此时PriorityQueue的结果是一个小根堆,如果想要结果是一个大根堆,需要修改Student类的compareTo方法或者比较器的compare方法,见包demo3的Test
class Student implements Comparable<Student>{
    public int age;
    public String name;
//    public Student(int age){
//        this.age = age;
//    }

    //只是比较对象的大小关系,返回值为正数/负数/0
    @Override
    public int compareTo(Student o) {
        return o.age - this.age;
        //但是这样就写死了，如果要比较姓名就需要进行重新修改代码，而不能直接调用---->此时可以使用equals进行对象的比较,或者使用comparator
    }

    @Override
    public String toString() {
        return "Student{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }


    //只是比较是否相等
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return age == student.age && Objects.equals(name, student.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(age, name);
    }
}
//比较器:对类的侵入性较弱
class AgeComparator implements Comparator<Student>{
    public int compare(Student o1, Student o2){
        return o2.age - o1.age;
    }
}
class NameComparator implements Comparator<Student>{
    public int compare(Student o1, Student o2){
        return o2.name.compareTo(o1.name);
    }
}

public class Test {
    public static void main(String[] args) {
        PriorityQueue<Student> priorityQueue = new PriorityQueue<>();
        Student s1 = new Student();
        s1.name = "zhangsan";
        s1.age = 10;
        Student s2 = new Student();
        s2.name = "ahangsan";
        s2.age = 12;
        priorityQueue.offer(s1);
        priorityQueue.offer(s2);
        //此时会使用Student的compareTo实现大根堆,下面就会输出年龄大的,即12岁的学术对象
        System.out.println(priorityQueue.poll());
        //或者使用比较器
//        AgeComparator ageComparator = new AgeComparator();
//        PriorityQueue priorityQueue1 = new PriorityQueue<>(ageComparator);
        NameComparator nameComparator = new NameComparator();
        PriorityQueue priorityQueue1 = new PriorityQueue<>(nameComparator);
        priorityQueue1.offer(s1);
        priorityQueue1.offer(s2);
        System.out.println(priorityQueue1.poll());//因为zhangsan大于ahangsan
    }

}

